package com.siyoumi.app.modules.sh.task.jm;

import com.siyoumi.component.api.jj.JJ;
import com.siyoumi.component.api.jj.robot.RobotErr;
import com.siyoumi.util.*;
import lombok.SneakyThrows;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;
import java.util.stream.Collectors;


//屈臣氏任务
@RestController
public class JmTaskWatsons
        extends TaskBase {
    @Override
    public void exec() {
        XLog.info(this.getClass(), "BEGIN:" + XDate.toDateTimeString());

        Map<String, String> arrTask = getArrTask();

        StringBuilder sendMsg = new StringBuilder();
        sendMsg.append("**watsons**\n\n");
        for (Map.Entry<String, String> task : arrTask.entrySet()) {
            String taskName = task.getKey();
            String returnStr = "";
            switch (taskName) {
                case "图片打卡":
                    returnStr = dokaHandle(task);
                    break;
                case "任务浏览":
                    returnStr = lookHandle(task);
                    break;
                default:
                    returnStr = commonHandle(task);
                    break;
            }

            sendMsg.append(returnStr);
        }

        //发jj
        JJ jj = JJ.getIns(RobotErr.class);
        jj.send(sendMsg.toString(), "", true);

        XLog.info(this.getClass(), "END:" + XDate.toDateTimeString());
    }


    //任务浏览
    @SneakyThrows
    public String lookHandle(Map.Entry<String, String> task) {
        String apiUrlArticleList = "https://sapi.watsons.xiao-bo.net/__api_java__/z_app/user_attr_up/web/get_article_picture_list?page=1&page_size=100&type=article&join_type=" +
                "&site_id=app.watsons&{wx_from}";

        StringBuilder sendMsg = new StringBuilder();
        String taskName = task.getKey();
        sendMsg.append("**" + taskName + "** \n\n");

        Map<String, String> arrWxFrom = getArrWxFrom();


        for (Map.Entry<String, String> entry : arrWxFrom.entrySet()) {
            String userName = entry.getKey();

            String apiUrl = apiUrlArticleList
                    .replace("{wx_from}", entry.getValue());
            XReturn r = requestApi(apiUrl);
            List<Map<String, Object>> listData = r.getData("list_data");
            List<Map<String, Object>> listData0 = new ArrayList<>(); //未完成的任务
            for (Map<String, Object> taskData : listData) {
                Integer joinType = (Integer) taskData.get("artpic_join_type");
                Integer state = (Integer) taskData.get("attch_state");
                if (state != null) {
                    if (1 == state) continue; //已完成
                }
                if (joinType != 1) continue; //非浏览任务

                listData0.add(taskData);
                break;
            }

            if (listData0.size() <= 0) {
                sendMsg.append(XStr.concat(userName, "-没有可执行的浏览任务", "\n\n"));
            }

            for (Map<String, Object> taskData : listData0) {
                String artpicId = (String) taskData.get("artpic_id");
                Integer s = (Integer) taskData.get("artpic_wait_time");
                String title = (String) taskData.get("artpic_title");
                String desc = (String) taskData.get("artpic_desc");

                XReturn rLanuch = lookLanuch("0", artpicId, entry.getValue());
                if (rLanuch.ok()) {
                    sendMsg.append(XStr.concat(userName, "-开始执行", title, desc, "\n\n"));
                    XApp.sleep(s);
                    sendMsg.append(XStr.concat(userName, "-停" + s, "秒", "\n\n"));

                    XReturn rLanuch1 = lookLanuch("1", artpicId, entry.getValue());
                    sendMsg.append(XStr.concat(userName, "-", rLanuch1.getErrMsg(), "\n\n"));
                } else {
                    sendMsg.append(XStr.concat(userName, "-开始执行", rLanuch.getErrMsg(), "\n\n"));
                }
            }
        }

        return sendMsg.toString();
    }

    private XReturn lookLanuch(String state, String artpicId, String wxFrom) {
        String apiUrlArticleLaunch = "https://sapi.watsons.xiao-bo.net/__api_java__/z_app/user_attr_up/web/launch?" +
                "master_openid={wx_from_0}&artpic_id={artpic_id}&state={state}&site_id=app.watsons&{wx_from}";

        String apiUrlLanuch = apiUrlArticleLaunch
                .replace("{state}", state)
                .replace("{artpic_id}", artpicId)
                .replace("{wx_from_0}", getWxFrom(wxFrom))
                .replace("{wx_from}", wxFrom);
        return requestApi(apiUrlLanuch);
    }


    //打卡(作废)
    @SneakyThrows
    public String dokaHandle(Map.Entry<String, String> task) {
        String apiUrlSignin = "https://sapi.watsons.xiao-bo.net/z_app/clock_act/web/zz_api__api_x__user_signin?" +
                "&site_id=app.watsons&clock_id={clock_id}&image={images}&text={text}&{wx_from}";
        apiUrlSignin = apiUrlSignin.replace("{clock_id}", task.getValue());


        StringBuilder sendMsg = new StringBuilder();
        String taskName = task.getKey();
        sendMsg.append("**" + taskName + "** \n\n");

        Map<String, String> arrWxFrom = getArrWxFrom();

        //预选择需要发的图片
        List<String> texts = new ArrayList<>();
        texts.add("打卡");
        texts.add("打卡啦");
        texts.add("今天天气很棒");
        texts.add("今天心情不错");
        texts.add("来了");
        texts.add("冲冲冲");

        List<String> imgs = getImgPaths();
        List<String> imgsUse = new ArrayList<>();
        while (true) {
            if (imgsUse.size() >= arrWxFrom.size()) {
                break;
            }

            int index = XApp.random(0, imgs.size() - 1);
            imgsUse.add(imgs.get(index));
            imgs.remove(index);
        }
        sendMsg.append("随机选择发送图片：" + imgsUse.stream().collect(Collectors.joining(",")));
        sendMsg.append("\n\n");

        Integer indexImg = 0;
        for (Map.Entry<String, String> entry : arrWxFrom.entrySet()) {
            String userName = entry.getKey();
            //发起
            int indexTxt = XApp.random(0, texts.size() - 1);

            String apiUrl = apiUrlSignin
                    .replace("{wx_from}", entry.getValue())
                    .replace("{images}", imgsUse.get(indexImg))
                    .replace("{text}", texts.get(indexTxt));
            XReturn r = requestApi(apiUrl);
            sendMsg.append(XStr.concat(userName, "-打卡:", r.getErrMsg(), "\n\n"));
            //
            indexImg++;
        }

        return sendMsg.toString();
    }

    //图片路径
    public List<String> getImgPaths() {
        String s = "_upload/_site/app.watsons/202210/6354b558d2aac-305b-aab7-406fbc4d0209.jpg|_upload/_site/app.watsons/202210/6354b5594d88a-32c8-b488-f444a3b4cfd2.jpg|_upload/_site/app.watsons/202210/6354b559a549e-3779-9cc7-a8b75ae4d9c1.jpg|_upload/_site/app.watsons/202210/6354b55a0dc16-38e8-8f4b-c6128c9f25b3.jpg|_upload/_site/app.watsons/202210/6354b55a673a0-33fa-8e2a-9c619d02b908.jpg|_upload/_site/app.watsons/202210/6354b55ab975d-3483-8e9b-1e8e40573566.jpg|_upload/_site/app.watsons/202210/6354b55b34522-3f4a-b1af-b149bb759ec7.jpg|_upload/_site/app.watsons/202210/6354b55b72c1d-358b-93d4-9fb3f6173133.jpg|_upload/_site/app.watsons/202210/6354b55bd8d40-3fb7-9f2a-c74cd31dc1bd.jpg|_upload/_site/app.watsons/202210/6354b55c36b3b-39f3-9bea-0bdce98dd08a.jpg|_upload/_site/app.watsons/202210/6354b55c7f6e1-3305-9779-a6976e21458e.jpg|_upload/_site/app.watsons/202210/6354b55d57403-37dd-ad39-b98a7b7054b7.jpg|_upload/_site/app.watsons/202210/6354b55db5ad5-30a8-83e3-96784c806b14.jpg|_upload/_site/app.watsons/202210/6354b55e68992-3420-9ad6-95ae01befdc8.jpg|_upload/_site/app.watsons/202210/6354b55f109a8-3b48-8aac-cede6888fa8f.jpg|_upload/_site/app.watsons/202210/6354b55fb924b-3475-9ada-f237faf0b9ae.jpg|_upload/_site/app.watsons/202210/6354b56065e2a-321c-9d19-107174ec461e.jpg|_upload/_site/app.watsons/202210/6354b56119b25-3d60-8781-9c317a7da953.jpg|_upload/_site/app.watsons/202210/6354b561d284e-3cb6-867c-5463e77d82b1.jpg|_upload/_site/app.watsons/202210/6354b56279091-339d-ac53-a3591e087a3a.jpg|_upload/_site/app.watsons/202210/6354b563c9738-3ae6-90a2-1b777b494120.jpg|_upload/_site/app.watsons/202210/6354b564a95c9-345b-bc22-a6dd713a6945.jpg";
        return new ArrayList<>(Arrays.asList(s.split("\\|")));
    }

    @Override
    public Map<String, String> getArrTask() {
        Map<String, String> arr = new HashMap<>();
        //arr.put("图片打卡", "clock-618203fd2cd5b-3866-bb70-048c79b66826");
        arr.put("任务浏览", "");
        return arr;
    }

    @Override
    public Map<String, String> getArrWxFrom() {
        Map<String, String> arr = new HashMap<>();
        //arr.put("佬大", "wx_from=oINFP5H3UvLXMv1KZ8D09kCD0ELY&wx_from_enc=NjEyMmM1ZYjBsT1JsQTFTRE5WZGt4WVRYWXhTMW80UkRBNWEwTkVNRVZNV1E9PQ==");
        arr.put("夫人", "wx_from=oINFP5IDVmANNDhcuq1cazsLIQYA&wx_from_enc=YmY4OTU4OYjBsT1JsQTFTVVJXYlVGT1RrUm9ZM1Z4TVdOaGVuTk1TVkZaUVE9PQ==");
        arr.put("空", "wx_from=oINFP5CNDUCoAoGOgizKztBcmSS0&wx_from_enc=ZDg3ZjViZYjBsT1JsQTFRMDVFVlVOdlFXOUhUMmRwZWt0NmRFSmpiVk5UTUE9PQ==");

        return arr;
    }
}
